#include "ffmpegutil.h"

extern "C" {

    #include <libswscale/swscale.h>
}

FFmpegUtil::FFmpegUtil()
{

}

int FFmpegUtil::yuvToRGB(YUVDataSpec &inYuvDataSpec, YUVDataSpec &outYuvDataSpec)
{

    uint8_t* inYuvData[4],* outYuvData[4];
    int inStrides[4], outStrides[4];

    int res = 0;

    SwsContext* context = sws_getContext(inYuvDataSpec.getWidth(),inYuvDataSpec.getHeight(),inYuvDataSpec.getFormat(),
                   outYuvDataSpec.getWidth(),outYuvDataSpec.getHeight(),outYuvDataSpec.getFormat(),
                   SWS_BILINEAR,nullptr,nullptr,nullptr);

    if(context == nullptr) {

        qDebug() << "sws_getContext fail";
        return 1;
    }

    res = av_image_alloc(inYuvData,inStrides,inYuvDataSpec.getWidth(),inYuvDataSpec.getHeight(),inYuvDataSpec.getFormat(),1);

    if(res < 0) {

        av_freep(&context);
        qDebug() << "av_image_alloc";
        return res;
    }

    memcpy(inYuvData[0],inYuvDataSpec.getData(),inYuvDataSpec.imageSize());

    res = av_image_alloc(outYuvData,outStrides,outYuvDataSpec.getWidth(),outYuvDataSpec.getHeight(),outYuvDataSpec.getFormat(),1);

    if(res < 0) {

        av_freep(&inYuvData[0]);
        sws_freeContext(context);
        qDebug() << "av_image_alloc";
        return res;
    }

    sws_scale(context,inYuvData,inStrides,0,inYuvDataSpec.getHeight(),outYuvData,outStrides);

    outYuvDataSpec.setData(new char[outYuvDataSpec.imageSize()]);

//    outYuvDataSpec.getData()
    memcpy(outYuvDataSpec.getData(),outYuvData[0],outYuvDataSpec.imageSize());


    av_freep(&inYuvData[0]);
    av_freep(&outYuvData[0]);
    sws_freeContext(context);

    return 0;
}
